package com.zimin.cloud.web.filter;

import com.zimin.common.utils.ServerRequestContextHolder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;


/**
 * @author zimin
 * @since 2021/11/19 10:18 上午
 */
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class ServerWebFilter  implements WebFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerRequestContextHolder.put(request);
        return chain.filter(exchange)
                //Clear request save in ThreadLocal to prevent memory overflow
                .doFinally(s -> ServerRequestContextHolder.reset());
    }

    @Override
    public int getOrder() {
        return -20;
    }

}
